package com.unlcn.ils.wms.backend.service.sys.impl;

import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.bo.sys.PermissionsBO;
import com.unlcn.ils.wms.backend.bo.sys.RoleBO;
import com.unlcn.ils.wms.backend.dto.sysDTO.PermissNewDTO;
import com.unlcn.ils.wms.backend.dto.sysDTO.UserNewDTO;
import com.unlcn.ils.wms.backend.enums.StatusEnum;
import com.unlcn.ils.wms.backend.service.sys.PermissionsService;
import com.unlcn.ils.wms.backend.service.sys.RoleService;
import com.unlcn.ils.wms.base.mapper.extmapper.SysRoleCustomMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.SysRolePermissionsCustomMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysRoleMapper;
import com.unlcn.ils.wms.base.model.sys.SysRole;
import com.unlcn.ils.wms.base.model.sys.SysRolePermissions;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 
 * @ClassName: RoleServiceImpl 
 * @Description: 角色 service impl
 * @author laishijian
 * @date 2017年8月8日 上午10:21:40 
 *
 */
@Service
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private SysRoleMapper roleMapper;
	
	@Autowired
	private SysRoleCustomMapper roleCustomMapper;
	
	@Autowired
	private SysRolePermissionsCustomMapper rolePermissionsCustomMapper;
	
	@Autowired
	private PermissionsService permissionsService;
	
	@Override
	public Integer addRole(RoleBO roleBO) {
		
		SysRole role = new SysRole();
		BeanUtils.copyProperties(roleBO, role);
		
		validate(role);	//校验角色值
		
		if(null == roleBO.getPermissionsBOList() || roleBO.getPermissionsBOList().isEmpty()) {
			throw new BusinessException("权限不能为空");
		}
		
		//TODO 角色名重复验证
		
		role.setEnable(StatusEnum.RIGHT.getValue());	//设置状态
		role.setGmtCreate(new Date());	//设置创建时间
		role.setGmtModified(new Date());	//设置修改时间
		
		roleMapper.insert(role);
		
		Integer roleId = role.getId();	//角色id
		
		//新增角色权限关联
		List<SysRolePermissions> rolePermissionsList = new ArrayList<>();
		for(PermissionsBO permissionsBO : roleBO.getPermissionsBOList()) {
			SysRolePermissions permissions = new SysRolePermissions();
			permissions.setRoleId(roleId);
			permissions.setPermissionsId(permissionsBO.getId());
			rolePermissionsList.add(permissions);
		}
		rolePermissionsCustomMapper.insertBatch(rolePermissionsList);
		return roleId;
	}
	
	@Override
	public RoleBO findById(Integer id) throws Exception {
		
		SysRole role = roleMapper.selectByPrimaryKey(id);
		if(null != role) {
			RoleBO roleBO = new RoleBO();
			BeanUtils.copyProperties(role, roleBO);
			return roleBO;
		}else {
			return null;
		}
	}
	
	@Override
	public void updateRole(RoleBO roleBO) throws Exception {
		
		SysRole role = new SysRole();
		BeanUtils.copyProperties(roleBO, role);
		
		validate(role);	//验证角色
		
		RoleBO oldRoleBO = findById(role.getId());
		if(null == oldRoleBO) {
			throw new BusinessException("角色信息不存在");
		}
		
		role.setGmtModified(new Date());	//设置修改时间
		role.setEnable(role.getEnable() == null ? oldRoleBO.getEnable() : role.getEnable());
		roleMapper.updateByPrimaryKey(role);
	}
	
	@Override
	public void deleteByIds(String ids) throws Exception {
		roleCustomMapper.deleteByIds(Arrays.asList(ids.split(",")), StatusEnum.DELETE.getValue(),new Date());
	}
	
	@Override
	public List<RoleBO> list(RoleBO roleBO, PageVo pageVO) throws Exception{
		
		SysRole role = new SysRole();
		BeanUtils.copyProperties(roleBO, role);
		
		List<SysRole> roleList = roleCustomMapper.list(role, pageVO);
		
		List<RoleBO> roleBOList = new ArrayList<>();
		for (SysRole sysRole : roleList) {
			RoleBO newRoleBO = new RoleBO();
			BeanUtils.copyProperties(sysRole, newRoleBO);
			roleBOList.add(newRoleBO);
		}
		
		return roleBOList;
	}
	
	@Override
	public List<RoleBO> findByUserId(Integer userId) throws Exception{
		
		List<SysRole> roleList = roleCustomMapper.selectByUserId(userId, StatusEnum.RIGHT.getValue());
		//TODO 暂时只有这里用 不定义为常量
		String adminRoleName = "管理员";
		
		List<RoleBO> roleBOList = new ArrayList<>();
		for (SysRole sysRole : roleList) {
			RoleBO roleBO = new RoleBO();
			BeanUtils.copyProperties(sysRole, roleBO);
			
			//获取权限
			if(adminRoleName.equals(roleBO.getName())) {	//判断为管理员
				List<PermissionsBO> permissionsBOList = permissionsService.findAll();
				roleBO.setPermissionsBOList(permissionsBOList);
			}else {
				List<PermissionsBO> permissionsBOList = permissionsService.findByRoleId(sysRole.getId(), null);
				roleBO.setPermissionsBOList(permissionsBOList);
			}
			
			roleBOList.add(roleBO);
		}
		
		return roleBOList;
	}

	/**
	 * 根据用户id和仓库id获取对应的权限
	 *
	 * @param userId
	 * @param warehouseId
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<RoleBO> findByUserIdAndWarhouseId(Integer userId, Long warehouseId) throws Exception {
		List<SysRole> roleList = roleCustomMapper.selectByUseIdAnsWarehouseId(userId, warehouseId, StatusEnum.RIGHT.getValue());
		//TODO 暂时只有这里用 不定义为常量
		String adminRoleName = "管理员";

		List<RoleBO> roleBOList = new ArrayList<>();
		for (SysRole sysRole : roleList) {
			RoleBO roleBO = new RoleBO();
			BeanUtils.copyProperties(sysRole, roleBO);

			//获取权限
			if(adminRoleName.equals(roleBO.getName())) {	//判断为管理员
				List<PermissionsBO> permissionsBOList = permissionsService.findAll();
				roleBO.setPermissionsBOList(permissionsBOList);
			}else {
				List<PermissionsBO> permissionsBOList = permissionsService.findByRoleId(sysRole.getId(), null);
				roleBO.setPermissionsBOList(permissionsBOList);
			}

			roleBOList.add(roleBO);
		}

		return roleBOList;
	}

	/**
	 * 新版获取菜单权限数据
	 *
	 * @param userId
	 * @param warehouseId
	 * @return
	 * @throws Exception
	 */
	@Override
	public UserNewDTO findByUserIdAndWarhouseIdNew(Integer userId, Long warehouseId) throws Exception {
		UserNewDTO userNewDTO = new UserNewDTO();
		List<PermissNewDTO> permissNewDTOList = permissionsService.findPermissionsAndChildByParentIdAndUserId(null, userId, warehouseId);
		if (CollectionUtils.isNotEmpty(permissNewDTOList)){
			userNewDTO.setPermissionsBOList(permissNewDTOList);
		}
		return userNewDTO;
	}

	@Override
	public List<RoleBO> findAll() throws Exception {
		
		return findRoleAndChildByParentId(null);
	}
	
	@Override
	public List<RoleBO> findRoleAndChildByParentId(Integer parentId) throws Exception{
		
		List<SysRole> roleList = roleCustomMapper.selectByParentId(parentId);
		
		List<RoleBO> roleBOList = new ArrayList<>();
		for (SysRole sysRole : roleList) {
			RoleBO roleBO = new RoleBO();
			BeanUtils.copyProperties(sysRole, roleBO);
			//获取权限
			List<PermissionsBO> permissionsBOList = permissionsService.findByRoleId(sysRole.getId(), null);
			roleBO.setPermissionsBOList(permissionsBOList);
			//获取子权限
			roleBO.setChildRoleBOList(findRoleAndChildByParentId(roleBO.getId()));
			roleBOList.add(roleBO);
		}
		return roleBOList;
	}
	
	/**
	 * 
	 * @Title: validate 
	 * @Description: 校验角色属性
	 * @param @param role     
	 * @return void    返回类型 
	 * @throws 
	 *
	 */
	private void validate(SysRole role) {
		
		if(StringUtils.isBlank(role.getName())) {
			throw new BusinessException("角色名不能为空");
		}
		
	}
	
}
